package com.sanri.test.testmybatis.service;

import com.sanri.test.testmybatis.mapper.EmpMapper;
import com.sanri.test.testmybatis.po.Emp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class TransactionService {

    @Autowired
    EmpMapper empMapper;

    @Transactional
    public void insertData(){
        Emp emp = new Emp();
        emp.setEmpNo(100);
        emp.setEname("abc");
        empMapper.insert(emp);

        new Thread(){
            @Override
            public void run() {
                Emp one = empMapper.selectOneByEmpNo(100);
                System.out.println("查询结果为:"+one);
            }
        }.start();

        // 把问题放大
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        throw new IllegalArgumentException("参数错误");
    }

    @Transactional
    public void insertAndQuery(){
        Emp emp = new Emp();
        emp.setEmpNo(100);
        emp.setEname("abc");
        empMapper.insert(emp);

        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void afterCommit() {
                new Thread(){
                    @Override
                    public void run() {
                        // 这个线程会在方法结束并提交事务后才会执行
                        Emp one = empMapper.selectOneByEmpNo(100);
                        log.info("查询结果为:"+one);
                    }
                }.start();
            }
        });

        // 把问题放大
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

//        throw new IllegalArgumentException("参数错误");
    }
}
